package imse.team0.scalability.services;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import java.util.Properties;

/**
 * @author Eugen, 5/3/12 7:51 PM
 */
public class ESBLocalService implements IESBLocalService, InitializingBean {
    //public static final int PORT = 39999;
    //public static final String IP = "localhost";

    private static final Logger LOG = LoggerFactory.getLogger(ESBLocalService.class);

    private static final String prop_PRICE_CATALOG_IP = "priceCatalogIP";
    private static final String prop_PRICE_CATALOG_PORT = "priceCatalogPort";
    private static final String prop_ORDER_ID_FILTER = "orderIDFilter";

    private String vmManagerIP;
    private int vmManagerServicePort;

    public ESBLocalService(){
        LOG.debug("---------> ESBLocalService instance was created.");
    }

    public Properties getRouteProperties(String routeID) {
        // TODO: must retrieve the properties from the VM manager but currently just return some dummy values
        LOG.debug("exec: <getRouteProperties>, params:\n\trouteID="+routeID);
        Properties props = new Properties();
        props.put(prop_ORDER_ID_FILTER, System.currentTimeMillis()+"");
        props.put(prop_PRICE_CATALOG_IP, "192.168.2.3");
        props.put(prop_PRICE_CATALOG_PORT, "9092");
        return props;
    }

    public void setVmManagerIP(String ip){
        vmManagerIP = ip;
    }

    public void setVmManagerServicePort(int port){
        vmManagerServicePort = port;
    }

    // called after Spring Container set all properties on this bean
    public void afterPropertiesSet(){
        // start the Environment Manager socket listening loop
    }

/*    public static void main(String[] args) throws IOException {
        int listeningPort;
        if (args.length < 2) {
            System.out.println("Supply the IP address of the VM manager as first argument and port as second argument");
            System.exit(-1);
        }
        if (args.length == 2) {
            System.out.println("Port number for this service was not supplied. Using the default port = " + PORT);
            listeningPort = PORT;
        } else {
            listeningPort = Integer.parseInt(args[2]);
        }

        ESBLocalService service = new ESBLocalService();
        *//*TODO: implement the code to connect to the VM manager...
        * The thread used to interact with VM manager should be a non-daemon thread
        * since the VM manager is supposed to shutdown us with a special command*//*
        service.startListeningLoop(listeningPort);
    }*/

/*    private void startListeningLoop(final int portNum) throws IOException {
        Thread requestsServingThread = new Thread(new Runnable() {
            public void run() {
                try {
                    ServerSocket listenSock = new ServerSocket();
                    listenSock.setReuseAddress(true);
                    SocketAddress addr = new InetSocketAddress(IP, portNum);
                    listenSock.bind(addr, 5);
                    System.out.println("Local ESB Service started at address: ip="+IP+", port="+portNum);
                    while (true) {
                        Socket clientConn = listenSock.accept();
                        new Thread(new RequestExecutor(clientConn)).start();
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        *//*TODO: set this thread as daemon thread when will implement
        * the communication with VM manager.*//*
        //requestsServingThread.setDaemon(true);
        requestsServingThread.start();
    }*/
}

/*class RequestExecutor implements Runnable {

    private static final String cmd_GET_ROUTE_PROPERTIES = "getRouteProperties";

    private Socket connection;
    private static final String CMD_DELIM = ":";



    public RequestExecutor(Socket clientConn) {
        connection = clientConn;
    }

    public void run() {
        try {
            InputStream buff = connection.getInputStream();
            byte[] b_request = new byte[8192]; // assume request is never larger
            int bytesRead = buff.read(b_request);
            String request = new String(b_request, 0, bytesRead);
            System.out.println("Received following command:\n\t->" + request);
            // tokenize request
            final int dataOffset = request.indexOf(CMD_DELIM);
            String cmd = request.substring(0, dataOffset).trim();
            System.out.println(">> exec: <"+cmd+">");
            if (cmd.equalsIgnoreCase(cmd_GET_ROUTE_PROPERTIES)){
                execute_getRouteProperties(request.substring(dataOffset, bytesRead).trim());
            }
            buff.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            return;
        }
    }

    private void execute_getRouteProperties(String commandData){

        try {
            Writer out = new OutputStreamWriter(connection.getOutputStream());
            String orderFilterProperty = +"="++"#";
            String priceCatalogIPProperty = +"="++"#";
            String priceCatalogPortProperty = prop_PRICE_CATALOG_PORT+"="+"9092";
            out.write(orderFilterProperty+priceCatalogIPProperty+priceCatalogPortProperty);
            out.flush();
            out.close();
        }
        catch(Exception ex){
            System.out.println(ex.getCause()+"\nShutting down.");
            ex.printStackTrace();
            System.exit(-1);
        }
    }
}*/

